/*
 * Typical flow for working with Google Calendar Integration:
 * authorize first and then synchronize.
 * In GCalEngine, authorize includes both calling GoogleAuthorizor
 * to authorize the system and initializing Calendar service using
 * the authorizor.
 */
// @author A0105514U

/** @author A0105514U */

package gCalEngine;

import global.GlobalFields;
import global.InternetConnectionDetector;

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.api.services.calendar.Calendar;

public class GCalEngine {
	private GoogleSynchronizor synchronizor;
	private Calendar service;
	private boolean isAuthorized;
	private InternetConnectionDetector detector;
	private GoogleAuthorizor auth;
	private Logger logger;
	private FileHandler fh;
	
	private String GCALENGING_LOG_FILE_NAME = "GCalEngineLog.txt";
	
	public GCalEngine(){
		logger = Logger.getLogger(GCalEngine.class.getName());
		try{
			fh = new FileHandler(GCALENGING_LOG_FILE_NAME);
			logger.addHandler(fh);
		}catch(IOException e){
			// should not happen. Do nothing
		}
		// Prevent authorization window pops up as soon as the system is launched.
		// Users are given full control of when to connect
		while(GlobalFields.IS_FIRST_AUTH);
		detector = InternetConnectionDetector.getDetector();
		auth = new GoogleAuthorizor();
		synchronizor = new GoogleSynchronizor();
		initGCalEngine();
	}
	
	public void stopService(){
		service = null;
	}
	
	public void initGCalEngine(){
		// While the internet is not available, wait
		while(!detector.detect() && !GlobalFields.IS_TO_CONNECT);
		logger.log(Level.INFO,"Connection Requested.");
		logger.log(Level.INFO,"Starting to authorize Google Calendar");
		isAuthorized = auth.authorize();
		logger.log(Level.INFO, "Google Calendar Authorized.");
		initializeCalendarService();
	}
	
	private void initializeCalendarService(){
		Calendar.Builder builder = new Calendar.Builder(auth.getHttpTransport(),auth.getJsonFactory(),auth.getCredential());
		builder.setApplicationName("BeautyRoxy");
		builder.setHttpRequestInitializer(auth.getCredential());
		service = builder.build();
	}
	
	public void synchronize() throws IOException{
		if(service != null && synchronizor != null){
			logger.log(Level.INFO,"Starting to synchronize...");
			synchronizor.sync(service);
			logger.log(Level.INFO,"Synchronization finished.");
		}
	}
	
	public boolean isAuthorized(){
		return isAuthorized;
	}
}
